##########################################
## Copyright 2012-2013 Ceruti Francesco & contributors
##
## This file is part of LiSP (Linux Show Player).
##########################################

import time
from PyQt4 import QtCore


class MediaTime(QtCore.QThread):
    '''
    This class provide a multi-thread Qt-based timing system.
    If the progress signal is used in a thread-safe way (Qt.QueuedConnection),
    the signals pass across the threads.
    '''

    progress = QtCore.pyqtSignal(int)  # The signal emitted on progress

    def __init__(self, media, wait=1, autostart=True, parent=None):
        '''
        media     -> the media queried for time
        wait      -> the time from one signal and the next
        autostart -> if True the time start on media play
        '''
        super(MediaTime, self).__init__(parent)
        self.__media = media
        self.wait = wait
        self.__run = False  # Running status

        if(autostart):
            self.__media.onPlay.connect(lambda t: self.start())  # Auto-play connection

        # Stop connections
        self.__media.onStopped.connect(lambda t: self.onStop())  # on stop
        self.__media.onPaused.connect(lambda t: self.onPause())  # on pause
        self.__media.onEndOfStream.connect(lambda t: self.onStop())  # on eos
        self.__media.onError.connect(lambda t, e: self.onStop())  # on error

    def run(self):
        if(self.__media is not None):
            while(self.__run):
                self.progress.emit(self.__media.currentTime())
                time.sleep(self.wait)

    def stop(self):
        '''Change the running status to False'''
        self.__run = False

    def start(self):
        '''Change the running status to True and starts'''
        self.__run = True
        super().start()

    def onPause(self):
        '''Stop and emit the media current time'''
        self.stop()
        self.progress.emit(self.__media.currentTime())

    def onStop(self):
        '''Stop and emit 0 as current time'''
        self.stop()
        self.progress.emit(0)
